package com.txd.mofa.shouye.fgt;

import android.Manifest;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.kongzue.baseframework.interfaces.Layout;
import com.kongzue.baseframework.util.JumpParameter;
import com.kongzue.baseframework.util.OnJumpResponseListener;
import com.kongzue.baseframework.util.OnPermissionResponseListener;
import com.kongzue.baseokhttp.HttpRequest;
import com.kongzue.baseokhttp.listener.ResponseListener;
import com.kongzue.baseokhttp.util.Parameter;
import com.kongzue.dialog.v2.WaitDialog;
import com.ninetaildemonfox.zdl.ninetails.map.JSONUtils;
import com.txd.mofa.R;
import com.txd.mofa.adapter.FragmentAdp;
import com.txd.mofa.base.BaseFgt;
import com.txd.mofa.bean.FlagBean;
import com.txd.mofa.bean.ShouyeBean;
import com.txd.mofa.fabu.aty.XiangceAty;
import com.txd.mofa.login.StartAty;
import com.txd.mofa.net.NetUtils;
import com.txd.mofa.shouye.aty.SeachAty;
import com.txd.mofa.shouye.aty.ShaiXuanAty;
import com.txd.mofa.view.CustomViewpager;
import com.txd.mofa.view.HXLinePagerIndicator;
import com.txd.mofa.view.MyViewPager;
import com.txd.mofa.view.ScaleTransitionPagerTitleView;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


@Layout(R.layout.fgt_home)
public class HomeFgt extends BaseFgt {

    @BindView(R.id.ll)
    LinearLayout ll;
    Unbinder unbinder;
    @BindView(R.id.iv_shaixuan)
    ImageView ivShaixuan;
    @BindView(R.id.iv_gengduo)
    ImageView ivGengduo;
    CustomViewpager viewpager;
    TagFlowLayout flow;
    LinearLayout llGengduo;
    @BindView(R.id.view)
    View view;
    @BindView(R.id.tv_seach)
    TextView tvSeach;
    private NestedScrollView sc;
    private MagicIndicator magicIndicator;
    private LinearLayout ll_sou,ll_net;

    private List<String> listTitle = new ArrayList<>();
    private List<Fragment> list = new ArrayList<>();
    private TagAdapter adapter;

    public static HomeFgt newInstance() {

        Bundle args = new Bundle();
        HomeFgt fragment = new HomeFgt();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void initViews() {
        super.initViews();
        sc = findViewById(R.id.sc);
        llGengduo = findViewById(R.id.ll_gengduo);
        ll_sou = findViewById(R.id.ll_sou);
        magicIndicator = findViewById(R.id.magic_indicator);
        viewpager = findViewById(R.id.viewpager);
        flow = findViewById(R.id.flow);
        ll_net = findViewById(R.id.ll_net);

    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {

        ll_net.setVisibility(View.GONE);
        faxingList();

    }

    @Override
    protected void onNetworkDisConnected() {

    }

    @Override
    public void onResume() {
        super.onResume();

        Huoqu();

        requestPermission(new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, new OnPermissionResponseListener() {
            @Override
            public void onSuccess(String[] permissions) {
            }

            @Override
            public void onFail() {

            }
        });
        faxingList();
    }

    private int pos = 0;

    private void faxingList() {

        if (flag == false) {
            ll_net.setVisibility(View.VISIBLE);
        }

        HttpRequest.POST(me, HairTitle, new Parameter(), new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {
                if (error == null) {
                    Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                    if (map.get("code").equals("1")){

                        ArrayList<Map<String, String>> data = JSONUtils.parseKeyAndValueToMapList(map.get("data"));

                        if (listTitle.size() == 0) {

                            for (int i = 0; i < data.size(); i++) {
                                listTitle.add(data.get(i).get("name"));
                            }

                            for (int i = 0; i < listTitle.size(); i++) {
                                list.add(FaxingFgt.newInstance(""+i, "1",data.get(i).get("id")));
                            }

                            FragmentAdp fragmentAdp = new FragmentAdp(getChildFragmentManager(), list, listTitle);
                            viewpager.setAdapter(fragmentAdp);
                            viewpager.setOffscreenPageLimit(list.size());


                            viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                                @Override
                                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                                }

                                @Override
                                public void onPageSelected(int position) {
                                    viewpager.resetHeight(position);
                                    pos = position;
                                    llGengduo.setVisibility(View.GONE);
                                    flag1 = false;
                                    EventBus.getDefault().postSticky(new FlagBean(position+""));
                                    sc.scrollTo(0,0);
                                }

                                @Override
                                public void onPageScrollStateChanged(int state) {

                                }
                            });

                            CommonNavigator commonNavigator = new CommonNavigator(me);

                            //true 选项卡均分父布局宽度。这种情况仅仅在选项卡较少且文字比较短时候合适
                            //     如果文字很长，且选项卡很多，那么久会挤在一起密密麻麻，视觉上比较难看。
                            //通常设置false。
                            commonNavigator.setAdjustMode(false);

                            commonNavigator.setAdapter(new CommonNavigatorAdapter() {
                                @Override
                                public int getCount() {
                                    return listTitle == null ? 0 : listTitle.size();
                                }

                                @Override
                                public IPagerTitleView getTitleView(Context context, final int index) {
//                SimplePagerTitleView simplePagerTitleView = new SimplePagerTitleView(context);
                                    SimplePagerTitleView simplePagerTitleView = new ScaleTransitionPagerTitleView(context); //使用自定义
                                    simplePagerTitleView.setText(listTitle.get(index));
                                    simplePagerTitleView.setTextSize(19);
                                    simplePagerTitleView.setNormalColor(getResources().getColor(R.color.hui));
                                    simplePagerTitleView.setSelectedColor(getResources().getColor(R.color.huang));
                                    simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            viewpager.setCurrentItem(index);
                                        }
                                    });

                                    return simplePagerTitleView;
                                }

                                @Override
                                public IPagerIndicator getIndicator(Context context) {
                                    HXLinePagerIndicator indicator = new HXLinePagerIndicator(context);
                                    indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                                    indicator.setLineHeight(UIUtil.dip2px(context, 4));
                                    indicator.setLineWidth(UIUtil.dip2px(context, 20));
                                    indicator.setRoundRadius(UIUtil.dip2px(context, 3));

                                    indicator.setStartInterpolator(new AccelerateInterpolator());
                                    indicator.setEndInterpolator(new DecelerateInterpolator(2.0f));

                                    return indicator;
                                }
                            });

                            magicIndicator.setNavigator(commonNavigator);

                            ViewPagerHelper.bind(magicIndicator, viewpager);


                            adapter = new TagAdapter(listTitle) {
                                @Override
                                public View getView(FlowLayout parent, int position, Object o) {
                                    TextView tv = (TextView) LayoutInflater.from(me).inflate(R.layout.item_flow,
                                            flow, false);
                                    tv.setText((CharSequence) o);
                                    return tv;
                                }
                            };


                            flow.setAdapter(adapter);
                        }

                    }


                }else {
                    toast("网络异常");
                }
            }
        });
    }

    @Override
    public void onLazyLoad() {

    }

    @Override
    public void setEvents() {

        llGengduo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        ll_net.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                faxingList();
            }
        });

        ll_sou.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jump(SeachAty.class);
            }
        });


        flow.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {

                magicIndicator.onPageSelected(position);
                viewpager.setCurrentItem(position);

                llGengduo.setVisibility(View.GONE);
                flag1 = false;

                return true;
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    private boolean flag1 = false;
    private String renqun = "";
    private String lian = "";
    private String chang = "";

    @OnClick({R.id.iv_shaixuan, R.id.iv_gengduo, R.id.view,R.id.tv_seach})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_shaixuan:

                if (NetUtils.isNetworkAvailable(me)) {
                    jump(ShaiXuanAty.class, new JumpParameter().put("renqun", renqun).put("lian", lian).put("chang", chang), new OnJumpResponseListener() {
                        @Override
                        public void OnResponse(JumpParameter jumpParameter) {
                            if (jumpParameter != null) {
                                if (jumpParameter.getString("flag") != null) {
                                    if (jumpParameter.getString("flag").equals("111")) {
                                        ivShaixuan.setImageResource(R.mipmap.shaixuan);
                                        renqun = "";
                                        lian = "";
                                        chang = "";
                                    } else {
                                        ivShaixuan.setImageResource(R.mipmap.shaixuan_xuan);
                                        renqun = jumpParameter.getString("list1");
                                        lian = jumpParameter.getString("list2");
                                        chang = jumpParameter.getString("list3");
                                    }


                                    EventBus.getDefault().post(new ShouyeBean(renqun, lian, chang));

                                }
                            }
                        }
                    });
                }else {
                    Toast.makeText(me, "网络连接错误，请检查您的网络", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.tv_seach:
                jump(SeachAty.class);
                break;
            case R.id.view:
                llGengduo.setVisibility(View.GONE);
                flag1 = false;
                break;
            case R.id.iv_gengduo:

                if (flag1) {
                    llGengduo.setVisibility(View.GONE);
                    flag1 = false;
                } else {
                    Set<Integer> set = new HashSet<>();
                    set.add(pos);
                    llGengduo.setVisibility(View.VISIBLE);
                    adapter.setSelectedList(set);
                    flag1 = true;
                }

                break;
        }
    }
}
